﻿
namespace Huirui.Cavan.Application.MainBoundedContext.AttachmentModule
{
    using System;
    using Huirui.Cavan.Core.Extension;
    using Huirui.Cavan.Domain.MainBoundedContext.AttachmentModule;
    using Huirui.Cavan.Domain.MainBoundedContext.SearchModule;
    using Huirui.Cavan.Domain.Seedwork;
    using Spring.Context;
    using Spring.Context.Support;

    public class AttachmentAppService : BaseAppService<Attachment, AttachmentSearch, IAttachmentRepository>, IAttachmentAppService
    {
        private IApplicationContext SpringContext = null;
        private IFileUploadAppService FileUploadAppService { get; set; }

        private IAttachmentGroupRepository AttachmentGroupRepository { get; set; }

        public AttachmentGroup GetAttachmentGroupByID(int id)
        {
            return this.AttachmentGroupRepository.Get(id);
        }

        public override BoolGenericResult<Attachment> Delete(Attachment entity)
        {
            if (entity.IsNull())
            {
                throw new ArgumentException("");
            }

            this.SpringContext = ContextRegistry.GetContext();
            this.FileUploadAppService = this.SpringContext.GetObject("FileUploadAppService") as IFileUploadAppService;

            this.FileUploadAppService.DeleteFile(entity.FileUrl, entity.FileName);
            return base.Delete(entity);
        }

        public Attachment GetAttachmentByIDAndGroup(int id, AttachmentIdentifier.AttachmentGroup group)
        {
            AttachmentSearch attachmentSearch = SearchFactory.CreateAttachmentSearch(group, id);

            Attachment attachment = this.GetSingleBySearch(attachmentSearch);

            return attachment;
        }
    }
}
